﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

public partial class FSMS_Controls_Selection : SessionControlBase
{
	private Control[] m_SearchParams_Controls;
	private string[] m_SearchParams_DataType;

	public string SelectionID
	{
		get { return (string)ViewState["SelectionID"]; }
		set { ViewState["SelectionID"] = value; }
	}

	public string SelectionParams
	{
		get { return (string)ViewState["SelectionParams"] ?? ""; }
		set { ViewState["SelectionParams"] = value; }
	}

	public string HiddenParams
	{
		get { return (string)ViewState["HiddenParams"] ?? ""; }
		set { ViewState["HiddenParams"] = value; }
	}

	public int ColumnCount
	{
		get { return (int)(ViewState["ColumnCount"] ?? 3); }
		set { ViewState["ColumnCount"] = value; }
	}

	public int Width
	{
		get { return ViewState["Width"] != null ? (int)ViewState["Width"] : 500; }
		set { ViewState["Width"] = value; }
	}

	public string ShowColumns
	{
		get { return string.Join(",", GridView1.ShowColumns); }
		set { GridView1.ShowColumns = value.Split(new char[] { ',' }); }
	}

	public string ReturnColumns
	{
		get { return string.Join(",", GridView1.ReturnColumns); }
		set { GridView1.ReturnColumns = value.Split(new char[] { ',' }); }
	}

	public string OnSelect
	{
		get { return (string)(this.ViewState["OnSelect"] ?? ""); }
		set { this.ViewState["OnSelect"] = value; }
	}

	public string Title
	{
		get { return (string)(this.ViewState["Title"] ?? ""); }
		set { this.ViewState["Title"] = value; }
	}

	public string UserID
	{
		get { return (string)(this.ViewState["UserID"] ?? ""); }
		set { this.ViewState["UserID"] = value; }
	}

	public int PageSize
	{
		get { return (int)(ViewState["PageSize"] ?? 10); }
		set { ViewState["PageSize"] = value; }
	}

	private DataSet GetEmptyDataSet()
	{
		DataSet ds = new DataSet();
		DataTable dt = new DataTable();
		ds.Tables.Add(dt);
		return ds;
	}

	private DataView GetSelectionDataView()
	{
		if (GetSession(this.ClientID + "SelectionDataSet") == null)
			SetSession(this.ClientID + "SelectionDataSet", GetEmptyDataSet());

		return ((DataSet)GetSession(this.ClientID + "SelectionDataSet")).Tables[0].DefaultView;
	}

	private DataSet GetSelectionReportDataSet()
	{
		if (GetSession(this.ClientID + "SelectionReportDataSet") == null)
		{
            DataSet ds = Hipocrate.DB.DBConnection.GetData("GetReportDetails", new string[] { "UserID", "ID" }, new object[] { this.UserID, this.SelectionID });
			DataView dv4 = ds.Tables[4].DefaultView;
			dv4.RowFilter = "[PARAMETER_NAME] <> '@RETURN_VALUE' AND [PARAMETER_NAME] <> '@TABLE_RETURN_VALUE' AND [PARAMETER_NAME] <> '@UserID'";
			SetSession(this.ClientID + "SelectionReportDataSet", ds);
		}

		return (DataSet)GetSession(this.ClientID + "SelectionReportDataSet");
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		mpeSelection.BehaviorID = this.ClientID + "_selectionModalPopupBehavior";
		mpeSelection.OnOkScript = "onOk_Selection_" + this.ClientID + "()";
		GridView1.SelectionClientID = this.ClientID;

		btnSearch2.OnClick = "$get('" + btnSearch.ClientID + "').click();";
		tblTitle.Width = Unit.Pixel(this.Width);
		pnSearchParamsContainer.Width = Unit.Pixel(this.Width);
		tblSearch.Width = Unit.Pixel(this.Width);
		pnGridViewContainer.Width = Unit.Pixel(this.Width);

		if (!this.IsPostBack)
		{
			SetSession(this.ClientID + "SelectionDataSet", null);
			SetSession(this.ClientID + "SelectionReportDataSet", null);
			DataView dv0 = GetSelectionDataView();

			GridView1.SessionKey = GetSessionKey(this.ClientID + "SelectionDataSet");
			GridView1.SessionKeyIndex = 0;
			GridView1.SessionKeyFilter = dv0.RowFilter;
			GridView1.PageSize = this.PageSize;

			GridView1.DataSource = dv0;
			GridView1.DataBind();
		}

		DataSet ds = GetSelectionReportDataSet();
		DataView dv3 = ds.Tables[3].DefaultView;
		DataView dv4 = ds.Tables[4].DefaultView;

		TableRow tr = null;
		TableCell td = null;
		Control c = null;
		tr = new TableRow();
		int col = 0;
		int i = 0;
		m_SearchParams_Controls = new Control[dv4.Count];
		m_SearchParams_DataType = new string[dv4.Count];

		// parametrii ascunsi ai ferestrei de selectie
		ArrayList arHideParams = new ArrayList(HiddenParams.Split(new char[] { ',' }));

		foreach (DataRowView drv4 in dv4)
		{
			string strParameterName = drv4["PARAMETER_NAME"].ToString().Substring(1);
			string strParameterType = drv4["TYPE_NAME"].ToString();

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;
			td.Text = Tools.GetHeaderText(strParameterName);

			if (arHideParams.Contains(strParameterName))
				td.Visible = false;

			td = new TableCell();
			tr.Cells.Add(td);
			td.Wrap = false;

			dv3.RowFilter = "[Column] = '" + strParameterName + "'";
			if (strParameterType == "bit")
			{
				c = new DropDownList();
				c.ID = "ddl" + strParameterName;
				((DropDownList)c).Width = Unit.Pixel(150);
				((DropDownList)c).Items.Add(new ListItem("", ""));
				((DropDownList)c).Items.Add(new ListItem(Resources.GridView.No, "0"));
				((DropDownList)c).Items.Add(new ListItem(Resources.GridView.Yes, "1"));
			}
			else if (dv3.Count == 0)
			{
				c = new TextBox();
				c.ID = "txt" + strParameterName;
				((TextBox)c).Width = Unit.Pixel(150);
			}
			else
			{
				c = new DropDownList();
				c.ID = "ddl" + strParameterName;
				((DropDownList)c).Width = Unit.Pixel(150);
				int nDdl = GetTableNo(ds, 3, strParameterName);
				if (nDdl >= 0)
					FillDropDownList((DropDownList)c, ds.Tables[6 + nDdl].DefaultView, Convert.ToBoolean(dv3[0]["Translated"]));
			}

			td.Controls.Add(c);
			m_SearchParams_DataType[i] = strParameterType;
			m_SearchParams_Controls[i++] = c;

			if (strParameterType == "datetime" || strParameterType == "smalldatetime")
			{
				CalendarExtender ce = new CalendarExtender();
				ce.TargetControlID = c.ID;
				ce.CssClass = "MyCalendar";
				ce.Format = Tools.GetDateFormat();
				c.Parent.Controls.Add(ce);
			}

			if (arHideParams.Contains(strParameterName))
				td.Visible = false;
			else
			{
				col = (col + 1) % this.ColumnCount;
				if (col == 0)
				{
					tblSearchParams.Rows.Add(tr);
					tr = new TableRow();
				}
			}

			// parametrii ferestrei de selectie
			string[] selParams = SelectionParams.Split(new char[] { ',' });
			string[][] arParameters = GetSelectionParameters(selParams);
			for (int j = 0; j < selParams.Length; ++j)
			{
				if (strParameterName == arParameters[j][0])
				{
					if (c is TextBox)
					{
						((TextBox)c).Text = arParameters[j][1].ToString();
						((TextBox)c).ReadOnly = true;
					}
					else if (c is DropDownList)
					{
						((DropDownList)c).SelectedValue = arParameters[j][1].ToString();
						((DropDownList)c).Enabled = false;
					}
				}
			}
		}
		if (col != 0)
			tblSearchParams.Rows.Add(tr);
	}

	protected void btnSearch_Click(object sender, EventArgs e)
	{
		DataSet ds_ = GetSelectionReportDataSet();
		DataView dv0 = ds_.Tables[0].DefaultView;

		string[] arParamsNames;
		object[] arParams;

		DataView dv4_ = new DataView(ds_.Tables[4]);
		dv4_.RowFilter = "[PARAMETER_NAME] = '@UserID'";
		if (dv4_.Count > 0)
		{
			arParamsNames = new string[m_SearchParams_Controls.Length + 1];
			arParams = new object[m_SearchParams_Controls.Length + 1];
			arParamsNames[arParams.Length - 1] = "UserID";
			arParams[arParams.Length - 1] = this.UserID;
		}
		else
		{
			arParamsNames = new string[m_SearchParams_Controls.Length];
			arParams = new object[m_SearchParams_Controls.Length];
		}

		string strProcedureName = dv0[0]["ProcedureName"].ToString();
		for (int i = 0; i < m_SearchParams_Controls.Length; ++i)
		{
			arParamsNames[i] = m_SearchParams_Controls[i].ID.Substring(3);
			if (m_SearchParams_Controls[i] is TextBox)
				arParams[i] = Tools.GetSQLValue(((TextBox)m_SearchParams_Controls[i]).Text, m_SearchParams_DataType[i], Tools.GetLanguage(this.Page.Request));
			else if (m_SearchParams_Controls[i] is DropDownList)
				arParams[i] = Tools.GetSQLValue(((DropDownList)m_SearchParams_Controls[i]).SelectedValue, m_SearchParams_DataType[i], Tools.GetLanguage(this.Page.Request));
			else
				arParams[i] = Tools.GetSQLValue("");
		}

        DataSet ds = Hipocrate.DB.DBConnection.GetData(strProcedureName, arParamsNames, arParams);
		SetSession(this.ClientID + "SelectionDataSet", ds);

		GridView1.SessionKey = GetSessionKey(this.ClientID + "SelectionDataSet");
		GridView1.SessionKeyIndex = 0;
		GridView1.SessionKeyFilter = dv0.RowFilter;

		GridView1.DataSource = ds.Tables[0].DefaultView;
		GridView1.DataBind();
	}

	private void FillDropDownList(DropDownList d, DataView dv, bool bTranslated)
	{
		d.Items.Clear();
		foreach (DataRowView drv in dv)
		{
			ListItem li = new ListItem(bTranslated ? Tools.GetHeaderText(drv["Name"].ToString()) : drv["Name"].ToString(), drv["ID"].ToString());
			d.Items.Add(li);
		}
		d.Items.Insert(0, new ListItem("", ""));
	}

	private int GetTableNo(DataSet ds, int nParamsTable, string strParameterName)
	{
		DataView dv = new DataView(ds.Tables[nParamsTable], "Column = '" + strParameterName + "'", "", DataViewRowState.OriginalRows);
		if (dv.Count > 0)
			return dv.Table.Rows.IndexOf(dv[0].Row);
		else
			return -1;
	}

	protected string[][] GetSelectionParameters(string[] sparams)
	{
		string[][] paramsValues = new string[sparams.Length][];
		for (int j = 0; j < sparams.Length; j++)
			paramsValues[j] = sparams[j].Split(new char[] { '=' });

		return paramsValues;
	}
}
